import 'dart:io';

import 'package:collection/collection.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart' hide MenuController;
import 'package:flutter/material.dart' hide MenuController;
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_kit_bluetooth/flutter_kit_bluetooth.dart';
import 'package:flutter_soundmagus/common/define.dart';
import 'package:flutter_soundmagus/counter_observer.dart';
import 'package:flutter_soundmagus/page/cross/cross_controller.dart';
import 'package:flutter_soundmagus/page/cross/page_cross.dart';
import 'package:flutter_soundmagus/page/delay/delay_controller.dart';
import 'package:flutter_soundmagus/page/delay/page_delay.dart';
import 'package:flutter_soundmagus/page/delay/page_gain.dart';
import 'package:flutter_soundmagus/page/device/page_device.dart';
import 'package:flutter_soundmagus/page/eq/eq_controller.dart';
import 'package:flutter_soundmagus/page/eq/page_eq.dart';
import 'package:flutter_soundmagus/page/home/page_home.dart';
import 'package:flutter_soundmagus/page/inout/page_inout.dart';
import 'package:flutter_soundmagus/page/inout/summing_controller.dart';
import 'package:flutter_soundmagus/page/menu/menu_controller.dart';
import 'package:flutter_soundmagus/util/ble_helper.dart';
import 'package:flutter_soundmagus/util/util.dart';
import 'package:flutter_soundmagus/widget/widget.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:logger_flutter/logger_flutter.dart';
import 'package:path_provider/path_provider.dart';

import 'common/global.dart';
import 'model/model.dart';
import 'page/save/save_controller.dart';
import 'widget/alert/alert.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive); // 隐藏状态栏和底部导航栏
  requestPermission();

  final storage = await HydratedStorage.build(
    storageDirectory: await getTemporaryDirectory(),
  );
  final observer = CounterObserver();

  await Hive.initFlutter();
  await Hive.openBox('settings');

  try {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

    IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    print('Running on ${iosInfo.utsname.machine}'); // e.g. "iPod7,1"
  } catch (e) {}

  LogConsole.init(bufferSize: 2000);

  FlutterError.onError = (e) => logger.e(e);
  // HydratedBlocOverrides.runZoned(() => runApp(MyApp()), blocObserver: observer, storage: storage);
  SystemChrome.setPreferredOrientations(
      [Platform.isAndroid ? DeviceOrientation.landscapeLeft : DeviceOrientation.landscapeRight]).then((_) {
    HydratedBlocOverrides.runZoned(() {
      WidgetsFlutterBinding.ensureInitialized();

      runApp(MyApp());
    }, blocObserver: observer, storage: storage);
  });
}

Future<void> requestPermission() async {
  BluetoothManager.instance.requestPermissions();
  await Permission.microphone.request();
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // Map<int, Color> colorCodes = {
    //   50: Color.fromRGBO(0, 0, 0, .1),
    //   100: Color.fromRGBO(0, 0, 0, .2),
    //   200: Color.fromRGBO(0, 0, 0, .3),
    //   300: Color.fromRGBO(0, 0, 0, .4),
    //   400: Color.fromRGBO(0, 0, 0, .5),
    //   500: Color.fromRGBO(0, 0, 0, .6),
    //   600: Color.fromRGBO(0, 0, 0, .7),
    //   700: Color.fromRGBO(0, 0, 0, .8),
    //   800: Color.fromRGBO(0, 0, 0, .9),
    //   900: Color.fromRGBO(0, 0, 0, 1),
    // };

    //MaterialColor color = new MaterialColor(0xFF000000, colorCodes);

    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
          primaryColor: Color(0xffD16A28),
          unselectedWidgetColor: Colors.white,
          textTheme: Theme.of(context).textTheme.copyWith(
              bodySmall: TextStyle(color: Color(0xffD16A28)),
              bodyMedium: TextStyle(color: Colors.white),
              bodyLarge: TextStyle(
                  color: Color(
                    0xff9C9B9E,
                  ),
                  fontSize: 12)), //主题黄
          sliderTheme: Theme.of(context).sliderTheme.copyWith(
              trackHeight: 1,
              activeTrackColor: Colors.greenAccent,
              inactiveTrackColor: Colors.white,
              thumbColor: Colors.greenAccent,
              thumbShape: RoundSliderThumbShape(enabledThumbRadius: 5)),
          textButtonTheme: TextButtonThemeData(style: TextButton.styleFrom(textStyle: TextStyle(color: Colors.white))),
          buttonTheme: Theme.of(context).buttonTheme.copyWith(splashColor: Colors.transparent),
          dividerTheme: DividerThemeData(color: Colors.white //  <--- change the divider's color
              ),
          colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Color(0xffD16A28))),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
      builder: EasyLoading.init(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  final tabIcons = ['home', 'inout', 'cross', 'eq', 'delay'];

  final tabKeys = List.generate(6, (index) => GlobalKey());

  late List<Widget> tabs;

  final menuController = Get.put(MenuController());

  ///log开关
  var showLogConsole = kDevMode;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    _init();

    Get
      ..put(SaveController())
      ..put(EqController())
      ..put(CrossController())
      ..put(DelayController())
      ..put(MenuController())
      ..put(SummingController());

    //保存起来避免rebuild
    tabs = [
      PageHome(
        key: tabKeys[0],
      ),
      PageInout(key: tabKeys[1]),
      PageCross(key: tabKeys[2]),
      PageDelay(key: tabKeys[3]),
      PageGain(key: tabKeys[4]),
      PageEq(key: tabKeys[5]),
    ];

    //停留2s进入合频页面
    Future.delayed(Duration(seconds: 2), () => menuController.index.value = 1);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) {
      //background
      DataMng().save();
    } else if (state == AppLifecycleState.resumed) {
      //foreground
    } else if (state == AppLifecycleState.detached) {
      //退出app时断开连接
      FlutterBluePlus.connectedDevices.forEach((element) {
        element.disconnect();
      });
    }
    logger.d(state);
  }

  void _init() {
    //loading
    EasyLoading.instance
      ..maskType = EasyLoadingMaskType.custom
      ..displayDuration = const Duration(milliseconds: 2000)
      ..indicatorType = EasyLoadingIndicatorType.wave
      ..loadingStyle = EasyLoadingStyle.custom
      // ..indicatorSize = 45.0
      ..radius = 10.0
      ..progressColor = Colors.white
      ..backgroundColor = Color(0xffD16A28)
      ..indicatorColor = Colors.white
      ..textColor = Colors.white
      ..maskColor = Colors.white.withOpacity(0.2);

    //ble
    BleHelper();

    //上传初始化
    MsgParser.instance.onWrite.listen((value) {
      BleHelper.write(value);
    });
    //数据接收
    BleHelper().onReceived = (data) {
      MsgParser.instance.onReceived.add(data);
    };

    BleHelper().onConnect = (device) {
      Get.dialog(
          UnconstrainedBox(
            child: Image.asset(
              'loading_logo'.img,
              width: 130,
            ),
          ),
          barrierDismissible: false);
      Future.delayed(Duration(seconds: 2), () {
        Get.back();
        Get.find<MenuController>().showUpload();
      });

      //记录连接过的设备
      SharedPreferences.getInstance().then((value) => value.setString('_last_device_id', device.id.id));
    };

    _autoConnect();

    _sec();

    SystemChannels.navigation.setMethodCallHandler((call) {
      if (call.method == 'parseFile') {
        //传过来的文件内容
        DataMng.reset();
        showLoading(duration: Duration(seconds: 4));

        String str = call.arguments['content'];
        MsgParser.instance.parseWithString(str);
      }
      return Future.value();
    });

    DataMng().subject.listen((value) {
      MsgParser.done();
    });
  }

//自动回连
  _autoConnect() async {
    final pref = await SharedPreferences.getInstance();
    final id = pref.getString('_last_device_id');
    if (id == null) return;

    try {
      await for (final state in FlutterBluePlus.adapterState.timeout(const Duration(seconds: 5))) {
        if (state == BluetoothAdapterState.on) {
          print('BT Adapter turned ON');
          break;
        }
        print(state);
      }
    } catch (e) {
      print('Timeout when waiting for BT adapter ON');
    }

    await FlutterBluePlus.stopScan();

    FlutterBluePlus.startScan();
    FlutterBluePlus.scanResults.listen((event) {
      var result = event.firstWhereOrNull((element) => element.device.remoteId.toString() == id);
      if (result != null && !result.device.isConnected) {
        result.device.connect();
      }
    });
  }

  ///程序保护
  void _sec() async {
    // if (kDebugMode) {
    //   return;
    // }
    // try {
    //   final rs = await FlutterSec.checkRemote('com.edge.pbxdsp-king');
    //   if (!rs.isValid) {
    //     Get.dialog(FlutterSecWidget(rs: rs), barrierDismissible: rs.canClose);
    //   }
    //   if (rs.data != null && !kDevMode) {
    //     //不是测试包
    //     Future.delayed(Duration(seconds: 1), () {
    //       setState(() {
    //         showLogConsole = rs.data['showLogConsole'] == true;
    //       });
    //     });
    //   }
    // } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.black,
        resizeToAvoidBottomInset: false,
        floatingActionButton: showLogConsole ? _buildFloatingActionButton() : null,
        body: Stack(children: [
          ...tabs.map((e) {
            var i = tabs.indexOf(e);
            return Obx(() => Offstage(
                  child: e,
                  offstage: menuController.index.value != i,
                ));
          }).toList(),
          if (kDevMode)
            Align(
              child: Text(
                'Dev ${kBuildTime.toDateTime().toLocal()}',
                style: TextStyle(backgroundColor: Colors.yellow, color: Colors.black),
              ),
              alignment: Alignment.topCenter,
            ),
          // CupertinoButton(
          //   color: Colors.yellow,
          //   child: Text('模拟'),
          //   onPressed: () async {
          //     MsgParser.instance.testUpload();
          //   },
          // )
        ]));
  }

  Widget _buildBleBtn({bool connected = false}) {
    return TextButton(
        onPressed: () {
          Navigator.of(context).push(MaterialPageRoute(builder: (c) => FlutterBlueApp()));
        },
        child: Text(
          connected ? '已连接' : '未连接',
          style: TextStyle(color: connected ? Theme.of(context).colorScheme.secondary : Colors.red, fontSize: 12),
        ));
  }

  Widget _buildNav() {
    Widget item = Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        StreamBuilder<List<BluetoothDevice>>(
            stream: Stream.periodic(Duration(seconds: 2)).asyncMap((_) => FlutterBlue.connectedDevices),
            initialData: [],
            builder: (c, snapshot) {
              var device = snapshot.data?.firstOrNull;
              if (device == null) {
                return _buildBleBtn();
              }
              return StreamBuilder<BluetoothConnectionState>(
                  stream: device.connectionState,
                  builder: (context, snapshotDevice) {
                    var state = snapshotDevice.data;
                    return _buildBleBtn(connected: state == BluetoothConnectionState.connected);
                  });
            }),
        IconButton(
            icon: Image.asset(
              'asset/images/icon_upload.png',
              width: 24,
              height: 21,
            ),
            onPressed: () {
              //上传
              showCupertinoDialog(
                  context: context,
                  builder: (_) => CupertinoAlertDialog(
                        title: Text("提示"),
                        content: Text("上传数据将持续几分钟，确定是否上传？"),
                        actions: [
                          // Close the dialog
                          // You can use the CupertinoDialogAction widget instead
                          CupertinoButton(
                              child: Text('取消'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              }),
                          CupertinoButton(
                            child: Text('确定'),
                            onPressed: () async {
                              EasyLoading.show(status: 'loading...');
                              Future.delayed(Duration(seconds: 3), () {
                                EasyLoading.dismiss();
                              });
                              var isConnected = await BleHelper.isConnected();
                              if (isConnected) {
                                MsgParser.instance.start();
                              }
                              MsgParser.instance.testUpload();
                              Navigator.of(context).pop();
                            },
                          )
                        ],
                      ));
            }),
        IconButton(
            icon: Image.asset(
              'asset/images/icon_download.png',
              width: 24,
              height: 21,
            ),
            onPressed: () {
              //下载
            }),
        Spacer(),
        Container(
          margin: EdgeInsets.fromLTRB(50, 0, 10, 0),
          width: 60 * 5,
          // padding: EdgeInsets.all(3),
          // color: Colors.red,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: tabIcons
                .map(
                  (e) => GestureDetector(
                    onTap: () {
                      menuController.index.value = tabIcons.indexOf(e);
                    },
                    child: Obx(() => Image.asset(
                          menuController.index.value == tabIcons.indexOf(e)
                              ? 'asset/images/icon_tab_${e}_select.png'
                              : 'asset/images/icon_tab_$e.png',
                          width: 40,
                          height: 40,
                          fit: BoxFit.fill,
                        )),
                  ),
                )
                .toList(),
          ),
        ),
        Spacer(),
        Container(
          // color: Colors.yellow,
          // width: 120,
          height: 44,
          child: Row(
            children: [
              Image.asset(
                'asset/images/icon_logo.png',
                width: 90,
                height: 21,
              ),
              SizedBox(
                  height: 25,
                  width: 25,
                  child: Align(
                    alignment: Alignment.bottomRight,
                    child: Text(
                      'V1.1',
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                  ))
            ],
          ),
        ),
      ],
    );

    item = Container(
      height: 50,
      child: SafeArea(
        child: item,
        top: false,
        bottom: false,
      ),
      decoration: kBottomLineDecoration(),
    );
    return item;
  }

  Widget? _buildFloatingActionButton() {
    return FloatingActionButton(
      onPressed: () {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => LogConsole(
                      showClearButton: true,
                      showCloseButton: true,
                      onExport: onExport,
                    )));
      },
      tooltip: 'log',
      child: const Text('log'),
    );
  }

  onExport(v) {}
}
